package com.heima.user;

import com.alibaba.fastjson.JSON;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mrchen
 * @date 2022/7/4 11:15
 */
public class YongyouAiDemo {


    @Test
    public void idCardCheck(){
        Map map = idCardOcr("https://hmtt122.oss-cn-shanghai.aliyuncs.com/demo_idcard.png");
        System.out.println(map);
    }


    private Map idCardOcr(String idCardUrl){
        try {
            Map params = new HashMap();
            params.put("image",idCardUrl);
            params.put("imageType","URL");
            params.put("ocrType","0");
            Map map = executePostReq("8c9fc3c9a3344983ad2f04b69c7c09b4", "https://api.yonyoucloud.com/apis/dst/IdcardOCR/IdcardOCR", params);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用接口失败");
            return null;
        }
    }


    private Boolean idCardCheck(String idNumber,String userName){
        try {
            Map params = new HashMap();
            params.put("idNumber",idNumber);
            params.put("userName",userName);
            Map map = executePostReq("e6d19252759c4cd3b10b30a6c6fa6679", "https://api.yonyoucloud.com/apis/dst/matchIdentity/matchIdentity", params);
            return (Boolean) map.get("success");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用接口失败");
            return false;
        }
    }

    /**
     * 基础的post请求
     * @param apicode   用友秘钥
     * @param url   要调用接口路径
     * @param params  请求参数 map
     * @return
     */
    private Map executePostReq(String apicode,String url,Map params){
        // 1. 创建restTemplate客户端
        RestTemplate restTemplate = new RestTemplate();
        // 2. 封装请求头信息  apicode    contentType
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("apicode",apicode);
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        // 3. 封装请求参数   map  idNumber  userName
        HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(params), httpHeaders);
        // 4. 发起请求调用  得到返回结果
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        // 5. 将返回结果转为map对象
        String body = responseEntity.getBody();
        return JSON.parseObject(body, Map.class);
    }

}
